package com.nuc.thread.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description submit和invokeAll方法
 * @createTime 2021年08月01日 17:33:00
 */
@Slf4j
public class Test2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(2);

//        testSubmit(pool);
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(
                ()->{
                    log.debug("begin:1");
                    Thread.sleep(1000);
                    return "1";
                    },
                ()->{
                    log.debug("begin:2");
                    Thread.sleep(500);
                    return "2";
                },
                ()->{
                    log.debug("begin:3");
                    Thread.sleep(2000);
                    return "3";
                }
                ));

        futures.forEach(f->{
            try {
                log.debug(f.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });

    }

    private static void testSubmit(ExecutorService pool) throws InterruptedException, ExecutionException {
        Future<String> submit = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.debug("running...");
                return "ok";
            }
        });

        String s = submit.get();
        log.debug("得到的线程池处理结果:{}",s);
    }
}
